const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { verifyToken } = require('../middleware/auth');
const { formatResponse } = require('../utils/response');

// 提交留言
router.post('/', verifyToken, async (req, res) => {
  try {
    const { content, rating, productId } = req.body;
    const userId = req.userId;
    
    // 验证商品存在
    const [productCheck] = await pool.execute('SELECT id FROM products WHERE id = ?', [productId]);
    if (!productCheck.length) return res.status(404).json(formatResponse(404, '商品不存在'));
    
    // 验证用户购买记录
    const [orderCheck] = await pool.execute(
      `SELECT orders.id FROM orders JOIN order_items ON orders.id = order_items.order_id 
       WHERE orders.user_id = ? AND order_items.product_id = ? AND orders.status IN ('paid', 'completed')`,
      [userId, productId]
    );
    if (!orderCheck.length) return res.status(403).json(formatResponse(403, '您需要购买此商品才能留言'));
    
    // 验证未重复评价
    const [messageCheck] = await pool.execute(
      'SELECT id FROM messages WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    if (messageCheck.length) return res.status(400).json(formatResponse(400, '您已对该商品发表过评价'));
    
    await pool.execute(
      'INSERT INTO messages (user_id, product_id, content, rating, created_at) VALUES (?, ?, ?, ?, NOW())',
      [userId, productId, content, rating]
    );
    
    res.json(formatResponse(200, '留言提交成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '留言提交失败', error.message));
  }
});

// 获取商品留言列表
router.get('/products/:productId', async (req, res) => {
  try {
    const { productId } = req.params;
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    
    // 验证商品存在
    const [productCheck] = await pool.execute('SELECT id FROM products WHERE id = ?', [productId]);
    if (!productCheck.length) return res.status(404).json(formatResponse(404, '商品不存在'));
    
    // 获取分页留言
    const [messages] = await pool.execute(
      `SELECT messages.*, users.username, users.avatar 
       FROM messages JOIN users ON messages.user_id = users.id 
       WHERE product_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [productId, Number(limit), Number(offset)]
    );
    
    // 获取总数
    const [countResult] = await pool.execute(
      'SELECT COUNT(*) as total FROM messages WHERE product_id = ?',
      [productId]
    );
    
    res.json(formatResponse(200, '获取商品留言成功', {
      items: messages,
      total: countResult[0].total,
      page: Number(page),
      pages: Math.ceil(countResult[0].total / limit)
    }));
  } catch (error) {
    res.status(500).json(formatResponse(500, '获取商品留言失败', error.message));
  }
});

// 更新留言
router.put('/:id', verifyToken, async (req, res) => {
  try {
    const { content, rating } = req.body;
    const { id: messageId } = req.params;
    const userId = req.userId;
    
    // 验证所有权
    const [messageCheck] = await pool.execute(
      'SELECT id FROM messages WHERE id = ? AND user_id = ?',
      [messageId, userId]
    );
    if (!messageCheck.length) return res.status(404).json(formatResponse(404, '留言不存在或无权限更新'));
    
    await pool.execute(
      'UPDATE messages SET content = ?, rating = ?, updated_at = NOW() WHERE id = ?',
      [content, rating, messageId]
    );
    
    res.json(formatResponse(200, '留言更新成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '更新留言失败', error.message));
  }
});

// 删除留言
router.delete('/:id', verifyToken, async (req, res) => {
  try {
    const { id: messageId } = req.params;
    const userId = req.userId;
    
    // 验证所有权
    const [messageCheck] = await pool.execute(
      'SELECT id FROM messages WHERE id = ? AND user_id = ?',
      [messageId, userId]
    );
    if (!messageCheck.length) return res.status(404).json(formatResponse(404, '留言不存在或无权限删除'));
    
    await pool.execute('DELETE FROM messages WHERE id = ?', [messageId]);
    res.json(formatResponse(200, '留言删除成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '删除留言失败', error.message));
  }
});

module.exports = router;